import { Filter } from "mongodb"
import { db } from "../db"
import { FetchAPI, PageParams, Pager, ServerResult, WhiteListRule } from '../interface'
import { logger } from "f2e-server3"

const CONN_NAME = 'whitelist_rule'

export const white_list_all = async () => {
    const conn = db.collection<WhiteListRule>(CONN_NAME)
    const list = await conn.find({}).toArray()
    return {
        success: true,
        data: list
    } as ServerResult<WhiteListRule[]>
}

export const white_list: FetchAPI<PageParams<Filter<WhiteListRule>>, Pager<WhiteListRule>> = async (body) => {
    const { page = 1, pageSize = 10, params = {} } = body || {}
    const conn = db.collection<WhiteListRule>(CONN_NAME)
    const total = await conn.countDocuments(params)
    const list = await conn.find(params).skip((page - 1) * pageSize).limit(pageSize).toArray()
    return {
        success: true,
        data: {
            list,
            total,
            page,
            pageSize,
        }
    }
}

export const white_list_get: FetchAPI<{ host: string }, WhiteListRule | null> = async (body) => {
    const conn = db.collection<WhiteListRule>(CONN_NAME)
    const rule = await conn.findOne({ host: body.host })
    return {
        success: true,
        data: rule
    }
}

export const white_list_add: FetchAPI<WhiteListRule, WhiteListRule> = async (body, ctx) => {
    const conn = db.collection<WhiteListRule>(CONN_NAME)
    const createdBy = ctx?.loginUser?.username
    const rule: WhiteListRule = {
        ...body,
        createdAt: new Date(),
        createdBy,
    }
    const res = await conn.insertOne(rule)
    logger.info('whitelist_rule add:', rule.host, createdBy)
    return {
        success: true,
        data: {
            ...rule,
            _id: res.insertedId,
        }
    }
}

export const white_list_delete: FetchAPI<{ host: string }, WhiteListRule | null> = async (body, ctx) => {
    const conn = db.collection<WhiteListRule>(CONN_NAME)
    const rule = await conn.findOneAndDelete({ host: body.host })
    logger.info('whitelist_rule delete:', body.host, ctx?.loginUser?.username)
    return {
        success: true,
        data: rule,
    }
}
